package com.sikaryofficial.backend.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sikaryofficial.backend.domain.entity.FileMd5;
import com.sikaryofficial.backend.domain.mapping.FileMD5Mapping;
import com.sikaryofficial.backend.service.IFileMd5Service;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.domain.SysFile;
import com.sikaryofficial.system.api.model.FileMd5VO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author : qinjinyuan
 * @desc : 文件MD5管理服务
 * @date : 2023/10/30 15:39
 */
@Service
@Slf4j
@SuppressWarnings("unchecked")
public class FileMd5Manager {
    @Autowired
    private IFileMd5Service fileMd5Service;

    public SysFile getInfo(String md5) {
        FileMd5 fileMd5 = fileMd5Service.getOne(new LambdaQueryWrapper<FileMd5>()
                .eq(FileMd5::getMd5, md5)
                .eq(FileMd5::getDeletedVersion, 0L)
                .last("limit 1")
        );
        return FileMD5Mapping.INSTANCE.coverToSysFile(fileMd5);
    }

    @Async("asyncTaskExecutor")
    public Boolean save(FileMd5VO fileMd5) {
        FileMd5 fileMd51 = FileMD5Mapping.INSTANCE.coverToEntity(fileMd5);
        if (Objects.isNull(fileMd51.getFileMd5Id())) {
            fileMd51.setFileMd5Id(IdWorker.getId());
            fileMd51.setCreatedTime(new Date());
            fileMd51.setCreatedBy(SecurityUtils.getUserId());
        } else {
            fileMd51.setUpdatedTime(new Date());
            fileMd51.setUpdatedBy(SecurityUtils.getUserId());
        }
        fileMd5Service.saveOrUpdate(fileMd51);
        return true;
    }
}
